package com.xhui.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhui.controller.dto.AjaxResult;
import com.xhui.entity.Book;
import com.xhui.service.IBookService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController //声明此类需要创建，且使用Restful风格进行开发:方法的返回值会默认传递给前端
@RequestMapping("/books") // 设置该类的请求路径映射
public class BookController {

    @Resource
    private IBookService bookService;

    @GetMapping
    public AjaxResult< List<Book> > getAll(){

        return new AjaxResult< List<Book> >(true, bookService.list());
    }

    @PostMapping
    public AjaxResult<Book> save(@RequestBody Book book) throws IOException {
        if( book.getName().equals("123") ){throw new IOException();}
        boolean flag = bookService.save(book);
        return new AjaxResult<>(flag, flag ? "添加成功^_^": "添加失败-_-！");
    }

    @PutMapping
    public AjaxResult<Book> update(@RequestBody Book book){
        System.out.println("有人对我进行编辑请求...");
        System.out.println("有人对我进行编辑请求...");
        AjaxResult<Book> result = new AjaxResult<>();
        result.setFlag(bookService.updateById(book));
        return result;
    }

    @DeleteMapping("/{id}")
    public AjaxResult<Book> delete(@PathVariable Integer id){
        return new AjaxResult<Book>(bookService.delete(id));
    }

    // http://localhost/books/10
    @GetMapping("/{id}") //10
    public AjaxResult<Book> getById(@PathVariable Integer id){
        System.out.println("get by  ......");
        System.out.println("get by  ......");
        System.out.println("get by  ......");
        return new AjaxResult<Book>(true, bookService.getById(id));
    }

    /*@GetMapping("/{currentPage}/{pageSize}")
    public AjaxResult< IPage<Book> > getPage(@PathVariable int currentPage, @PathVariable int pageSize){
        IPage<Book> page = bookService.getPage(currentPage, pageSize);
        // 如果当前页码值 大于 总页码值，那么重写执行查询操作，使用最大页码值作为当前页码值
        if( currentPage > page.getPages() ){
            page = bookService.getPage((int)(page.getPages()), pageSize);
        }
        return new AjaxResult< IPage<Book> >(true, page);
    }*/

    @GetMapping("/{currentPage}/{pageSize}")
    public AjaxResult< IPage<Book> > getPage(@PathVariable int currentPage, @PathVariable int pageSize, Book book){
        System.out.println("test hot deploy ...");
        System.out.println("test hot deploy ...");
        IPage<Book> page = bookService.getPage(currentPage, pageSize, book);
        // 如果当前页码值 大于 总页码值，那么重写执行查询操作，使用最大页码值作为当前页码值
        if( currentPage > page.getPages() ){
            page = bookService.getPage((int)(page.getPages()), pageSize, book);
        }
        return new AjaxResult< IPage<Book> >(true, page);
    }
}
